package com.lixun.passwordbook.slice;

import com.lixun.passwordbook.HomeAbility;
import com.lixun.passwordbook.ResourceTable;
import com.lixun.passwordbook.WelcomeAbility;
import com.lixun.passwordbook.pojo.Colors;
import com.lixun.passwordbook.pojo.Data;
import com.lixun.passwordbook.util.FileData;
import com.lixun.passwordbook.provider.Provider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ListDialog;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainStart");
    private static final String BASE_URI = "dataability:///com.lixun.passwordbook.DataAbility";
    private static final String DATA_PATH = "/pwb";
    private static final String DB_COLUMN_ID = "id";
    private static final String DB_COLUMN_NICKNAME = "nickname";
    private static final String DB_COLUMN_USERNAME = "username";
    private static final String DB_COLUMN_PASSWOED = "password";
    private static final String DB_COLUMN_TYPE = "type";
    private static final String DB_COLUMN_EXPLAIN = "explain";
    private static final String DB_COLUMN_MODIFYTIME = "modifytime";
    private DataAbilityHelper databaseHelper;
    private StackLayout ability_main;
    private Context context;
    private Context mContext;
    private FileData fileData;
    private static boolean isFirst = true;
    public static void setIsFirst(boolean isFirst) {
        MainAbilitySlice.isFirst = isFirst;
    }
    public static boolean getIsFirst() {
        return isFirst;
    }
    //dialog
    public static final int DIALOG_BOX_WIDTH = 300;
    public static final int DIALOG_BOX_HEIGHT = 800;
    /**
     * DIALOG_BOX_CORNER_RADIUS
     */
    public static final float DIALOG_BOX_CORNER_RADIUS = 36.0f;
    /**
     * DIALOG_BOX_WIDTH
     */
    public static final int DIALOG_BOX_CORNER_WIDTH = 984;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
//        ability_main = (StackLayout) findComponentById(ResourceTable.Id_stack_layout);
        context = getApplicationContext();
        fileData = new FileData();
        mContext = this;
        //是否第一次启动app
        firstRun();
        // 创建按钮
        createAddBtn();
        createTypeBtn();
        createSetBtn();
        databaseHelper = DataAbilityHelper.creator(this);
        //设置导航栏颜色
        setStatusBarColor();

    }

    @Override
    public void onActive() {
        super.onActive();
        //设置深色模式转换
        colorMode();
        //设置分类
        Button typeBtn = (Button) findComponentById(ResourceTable.Id_main_type);
        String type = typeBtn.getText();
        if (type.equals("全部")) {
            //构建item
            initListContainer(getData());
        } else {
            //构建item
            initListContainer(getTypeData(type));
        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onInactive() {
        super.onInactive();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 颜色模式切换
     */
    private void colorMode(){
        Button mainType = (Button) findComponentById(ResourceTable.Id_main_type);
        Button mainSet = (Button) findComponentById(ResourceTable.Id_main_set);
        StackLayout ability_main = (StackLayout) findComponentById(ResourceTable.Id_stack_layout);
        boolean dark_mode = Colors.getDarkMode();
        ShapeElement shapeElement = new ShapeElement();
        ShapeElement typeElement = new ShapeElement();
        Color color;
        Resource bgResource=null;
        if (dark_mode){
            HiLog.info(LABEL, "设置为深色模式");
            shapeElement.setRgbColor(Colors.backgroundColorDark);
            typeElement = new ShapeElement(mContext,ResourceTable.Graphic_main_type_button_dark);
            color = Colors.textColorDark;
        } else {
            HiLog.info(LABEL, "设置为常规模式");
            shapeElement.setRgbColor(Colors.backgroundColor);
            typeElement = new ShapeElement(mContext,ResourceTable.Graphic_main_type_button);
            color = Colors.textColor;
        }
        try {
            if (dark_mode){
                bgResource =getResourceManager().getResource(ResourceTable.Media_main_more_dark);
            } else {
                bgResource =getResourceManager().getResource(ResourceTable.Media_main_more);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        ability_main.setBackground(shapeElement);
        mainType.setTextColor(color);
        mainType.setBackground(typeElement);
        //设置按钮背景图片
        PixelMapElement pixBg=new PixelMapElement(bgResource);
        mainSet.setAroundElements(null,null,pixBg,null);
    }

    /**
     * 是否第一次启动app
     */
    private void firstRun(){
        StackLayout stackLayout = (StackLayout) findComponentById(ResourceTable.Id_stack_layout);
        boolean first = fileData.getBoolean(context,"first",true);
        if (first) {
            stackLayout.setVisibility(Component.HIDE);
            toWelcome();
        } else {
            // 是否隐藏界面
            if (isFirst) {
                stackLayout.setVisibility(Component.HIDE);
                toHome();
            } else {
                stackLayout.setVisibility(Component.VISIBLE);
            }
        }
    }

    /**
     * 创建类型按钮
     */
    private void createTypeBtn() {
        Component component = findComponentById(ResourceTable.Id_main_type);
        Button typeBtn;
        if (component instanceof Button) {
            typeBtn = (Button) component;
            typeBtn.setClickedListener(view -> {
                showListDialog();
            });
        }
    }

    /**
     * /创建添加按钮
     */
    private void createAddBtn() {
        Component component = findComponentById(ResourceTable.Id_main_add);
        Button addBtn;
        if (component instanceof Button) {
            addBtn = (Button) component;
            addBtn.setClickedListener(view -> toDetailed(0));
        }
    }

    /**
     * 创建设置按钮
     */
    private void createSetBtn() {
        Component component = findComponentById(ResourceTable.Id_main_set);
        Button addBtn;
        if (component instanceof Button) {
            addBtn = (Button) component;
            addBtn.setClickedListener(view -> toSet());
        }
    }

    /**
     * 构建页面
     * @param getData
     */
    private void initListContainer(ArrayList<Data> getData) {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        List<Data> list = getData;
        Provider provider = new Provider(list, this,this);
        //批量添加item
        listContainer.setItemProvider(provider);
        //设置item触发器，实现页面跳转
        listContainer.setItemClickedListener((container, component, position, id) -> {
            //设置需要传递的数据
            Data item = (Data) listContainer.getItemProvider().getItem(position);
            //Ability跳转
            HiLog.info(LABEL,"跳转前");
            toDetailed(item.getId());
        });
    }

    /**
     * 跳转到详情界面
     * @param id 需要展示详情的id
     */
    private void toDetailed(int id) {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.lixun.passwordbook.DetailedAbility")
                .build();
        intent.setOperation(operation);
        intent.setParam("id", id);
        startAbilityForResult(intent, 1);
    }

    /**
     * 跳转至设置界面
     */
    private void toSet() {
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName("com.lixun.passwordbook.SetAbility")
                .build();
        intent.setOperation(operation);
        startAbilityForResult(intent, 1);
    }

    /**
     * 获取数据
     * @return 返回数据数组
     */
    private ArrayList<Data> getData() {
        String[] columns = new String[]{DB_COLUMN_ID, DB_COLUMN_NICKNAME, DB_COLUMN_USERNAME, DB_COLUMN_PASSWOED, DB_COLUMN_TYPE, DB_COLUMN_EXPLAIN, DB_COLUMN_MODIFYTIME};
        // 构造查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.notEqualTo(DB_COLUMN_ID, 1);
        predicates.orderByDesc(DB_COLUMN_MODIFYTIME);
        try {
            ResultSet resultSet = databaseHelper.query(Uri.parse(BASE_URI + DATA_PATH),
                    columns, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                HiLog.info(LABEL, "query: resultSet is null or no result found");
                return null;
            }
            resultSet.goToFirstRow();
            ArrayList<Data> list = new ArrayList();
            Data data;
            do {
                int id = resultSet.getInt(resultSet.getColumnIndexForName(DB_COLUMN_ID));
                String nickname = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_NICKNAME));
                String username = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_USERNAME));
                String password = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_PASSWOED));
                String type = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_TYPE));
                String explain = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_EXPLAIN));
                String modifytime = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_MODIFYTIME));
                data = new Data(id, nickname, username, password, type, explain, modifytime);
                list.add(data);
            } while (resultSet.goToNextRow());
            return list;
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "query: dataRemote exception | illegalStateException");
        }
        return null;
    }

    /**
     * 通过类型获取数据
     * @param selectType 某一类型的名称
     * @return 返回某一类型的数据数组
     */
    private ArrayList<Data> getTypeData(String selectType) {
        String[] columns = new String[]{DB_COLUMN_ID, DB_COLUMN_NICKNAME, DB_COLUMN_USERNAME, DB_COLUMN_PASSWOED, DB_COLUMN_TYPE, DB_COLUMN_EXPLAIN, DB_COLUMN_MODIFYTIME};
        // 构造查询条件
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.notEqualTo(DB_COLUMN_ID, 1);
        predicates.equalTo(DB_COLUMN_TYPE, selectType);
        predicates.orderByDesc(DB_COLUMN_MODIFYTIME);
        try {
            ResultSet resultSet = databaseHelper.query(Uri.parse(BASE_URI + DATA_PATH),
                    columns, predicates);
            if (resultSet == null || resultSet.getRowCount() == 0) {
                HiLog.info(LABEL, "query: resultSet is null or no result found");
                return null;
            }
            resultSet.goToFirstRow();
            ArrayList<Data> list = new ArrayList();
            Data data;
            do {
                int id = resultSet.getInt(resultSet.getColumnIndexForName(DB_COLUMN_ID));
                String nickname = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_NICKNAME));
                String username = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_USERNAME));
                String password = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_PASSWOED));
                String type = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_TYPE));
                String explain = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_EXPLAIN));
                String modifytime = resultSet.getString(resultSet.getColumnIndexForName(DB_COLUMN_MODIFYTIME));
                data = new Data(id, nickname, username, password, type, explain, modifytime);
                list.add(data);
            } while (resultSet.goToNextRow());
            return list;
        } catch (DataAbilityRemoteException | IllegalStateException exception) {
            HiLog.error(LABEL, "query: dataRemote exception | illegalStateException");
        }
        return null;
    }

    /**
     * 跳转到密码认证界面
     */
    private void toHome() {
        Intent secondIntent = new Intent();
        // 指定待启动FA的bundleName和abilityName
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(HomeAbility.class.getName())
                .build();
        secondIntent.setOperation(operation);
        // 通过AbilitySlice的startAbility接口实现启动另一个页面
        startAbility(secondIntent);
        // 进入暂停状态通过onForeground可再次启动
        terminate();
    }

    /**
     * 跳转到欢迎界面
     */
    private void toWelcome() {
        Intent secondIntent = new Intent();
        // 指定待启动FA的bundleName和abilityName
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(getBundleName())
                .withAbilityName(WelcomeAbility.class.getName())
                .build();
        secondIntent.setOperation(operation);
        // 通过AbilitySlice的startAbility接口实现启动另一个页面
        startAbility(secondIntent);
        // 进入暂停状态通过onForeground可再次启动
        terminate();
    }

    /**
     * 设置状态栏颜色
     */
    private void setStatusBarColor() {
        getWindow().addFlags(WindowManager.LayoutConfig.MARK_TRANSLUCENT_NAVIGATION);
        getWindow().setStatusBarColor(Color.TRANSPARENT.getValue());
    }

    /**
     * 设置类型选择器
     */
    private void showListDialog() {
        Button resultText = (Button) findComponentById(ResourceTable.Id_main_type);
        String[] types = new String[]{"       全 部", "       默 认", "       网 站", "       游 戏", "       邮 箱", "       APP"};
        String[] types1 = new String[]{"全部", "默认", "网站", "游戏", "邮箱", "APP"};
        ListDialog listDialog = new ListDialog(this);
        listDialog.setAlignment(TextAlignment.LEFT);
        listDialog.setSize(DIALOG_BOX_WIDTH, DIALOG_BOX_HEIGHT);
        listDialog.setTitleText("  选择类型");
        listDialog.setCornerRadius(50);
        listDialog.setAutoClosable(true);
        listDialog.setItems(types);
        listDialog.setOnSingleSelectListener((iDialog, index) -> {
            resultText.setText(types1[index]);
            if (index == 0) {
                initListContainer(getData());
            } else {
                initListContainer(getTypeData(types1[index]));
            }
            iDialog.destroy();
        });
        listDialog.setOffset(60, -600);
        listDialog.show();
    }
}
